package com.hehua.web.observer.demo2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EventBus {

    private final Map<Class<?>, List<EventHandler<?>>> handlers = new HashMap<>();

    public <T> void subscribe(Class<?> eventType, EventHandler<T> handler) {
        handlers.computeIfAbsent(eventType, k -> new ArrayList<>()).add(handler);
    }

    public <T> void publish(T event) {
        List<EventHandler<?>> handlerList = handlers.get(event.getClass());
        if (handlerList != null) {
            for (EventHandler<?> eventHandler : handlerList) {
                ((EventHandler<T>) eventHandler).handle(event);
            }
        }
    }
}
